import numpy as np
from. import decision_tree


def build_random_forest(X, y, n_trees=10, min_samples_split=2, max_depth=10):
    forest = []
    n_samples = X.shape[0]

    for _ in range(n_trees):
        indices = np.random.choice(n_samples, n_samples, replace=True)
        X_sample = X[indices]
        y_sample = y[indices]

        tree = decision_tree.build_tree(X_sample, y_sample, min_samples_split, max_depth)
        forest.append(tree)

    return forest


def random_forest_predict(forest, X):
    predictions = []
    for x in X:
        tree_predictions = [decision_tree.predict_tree(tree, x) for tree in forest]
        most_common = max(set(tree_predictions), key=tree_predictions.count)
        predictions.append(most_common)

    return np.array(predictions)


def random_forest_classifier(X_train, y_train, X_test, n_trees=10, min_samples_split=2, max_depth=10):
    forest = build_random_forest(X_train, y_train, n_trees, min_samples_split, max_depth)
    y_pred = random_forest_predict(forest, X_test)
    return y_pred